﻿using System;

namespace Ewk.Math.ComputationTypes.Computables
{
    class ComputableFunction<T, TResult> : Computable<Function<T, TResult>>
        where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
        where TResult : struct, IComparable, IFormattable, IConvertible, IComparable<TResult>, IEquatable<TResult>
    {
        #region Constructors
        public ComputableFunction()
        {
        }

        public ComputableFunction(Function<T, TResult> value)
            : base(value)
        {
        }
        #endregion

        #region Overrides of Computable<Function<T,TResult>>
        public override Computable<Function<T, TResult>> Add(Computable<Function<T, TResult>> other)
        {
            if (other != null)
            {
                Value += other.Value;
            }

            return this;
        }

        public override Computable<Function<T, TResult>> Subtract(Computable<Function<T, TResult>> other)
        {
            if (other != null)
            {
                Value -= other.Value;
            }

            return this;
        }

        public override Computable<Function<T, TResult>> Multiply(Computable<Function<T, TResult>> other)
        {
            if (other != null)
            {
                Value *= other.Value;
            }
            else
            {
                Value = Factory.Zero.Value;
            }

            return this;
        }

        public override Computable<Function<T, TResult>> Divide(Computable<Function<T, TResult>> other)
        {
            if (other == null)
            {
                throw new DivideByZeroException();
            }

            Value /= other.Value;
            return this;
        }

        public override Computable<Function<T, TResult>> Sqrt()
        {
            Value = Function<T, TResult>.Sqrt(Value);
            return this;
        }

        public override Computable<Function<T, TResult>> Pow(Computable<Function<T, TResult>> power)
        {
            Value = power == null
                        ? Factory.One.Value
                        : Function<T, TResult>.Pow(Value, power.Value);

            return this;
        }

        #endregion

        public override bool AlmostEquals(Computable<Function<T, TResult>> other)
        {
            return Equals(other);
        }
    }
}